/**
* 版权声明：厦门睿商网络科技有限公司 版权所有 违者必究
* 日    期：2020-07-22
*/
package com.rzico.basics.controller;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.rzico.annotation.Log;
import com.rzico.base.BaseController;
import com.rzico.base.CommResult;
import com.rzico.basics.entity.Enterprise;
import com.rzico.basics.entity.Goods;
import com.rzico.basics.entity.Product;
import com.rzico.basics.service.*;
import com.rzico.entity.Filter;
import com.rzico.entity.Pageable;
import com.rzico.entity.PageResult;
import com.rzico.basics.entity.Bom;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.Api;
import com.rzico.util.StringUtils;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.HashMap;
import java.util.Map;
import java.util.Date;

/**
 * 商品清单控制层
 *
 * @author Rzico Boot
 * @version 1.0
 * @date 2020-07-22
 */
@Api(description = "商品清单接口")
@RestController
@RequestMapping("/admin/bom")
public class BomAdminController extends BaseController {

    @Autowired
    private BomService bomService;

    @Autowired
    private BomItemService bomItemService;

    @Autowired
    private EnterpriseService enterpriseService;

    @Autowired
    private ProductService productService;

    @Autowired
    private GoodsService goodsService;

    /**
     * 分页查询商品清单
     *
     * @return
    */
    @ApiOperation("分页查询商品清单")
    @GetMapping("/list")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "productId", value = "所属商品", dataType = "Long", paramType = "query") ,
            @ApiImplicitParam(name = "type", value = "类型 {0.产品,1:套餐,2:水票,3.称重,4.抻金}", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "itemProductName", value = "商品名称", dataType = "String", paramType = "query")
    })
    public CommResult<Bom> list(Long productId,Integer type,String itemProductName, Pageable pageable) {

        Map<String, Object> params = new HashMap<String, Object>();
        params = buildSortField(params, pageable);

        if (productId!=null){
           params.put("productId", productId);
        }
        if (type!=null){
            params.put("type", type);
        }
        if (itemProductName!=null){
            params.put("itemProductName", itemProductName);
        }

        Enterprise enterprise = enterpriseService.getCurrent();
        if (enterprise!=null) {
            params.put("enterpriseId", enterprise.getId());
        } else {
            return CommResult.error("没有开通企业");
        }

        params.put("deleted", 0);

        Page<Object> startPage = PageHelper.startPage(pageable.getPageNum(), pageable.getPageSize());
        List<Bom> list = bomService.selectList(params);
        PageResult<Bom> pageResult = new PageResult<Bom>(list, startPage.getTotal(), pageable);
        return CommResult.success(pageResult);

    }

    /**
     * 查询单条商品清单
     *
     * @return
    */
    @ApiOperation("查询单条商品清单")
    @GetMapping("/find/{id}")
    public CommResult<Bom> find(@PathVariable Long id) {

        Bom result = bomService.findById(id);

        Map<String,Object> data = new HashMap<>();
        data.put("bom",result);

        result.setItemList(bomItemService.getItemList(id));

        return CommResult.success(data);

    }

    /**
     * 保存商品清单
     *
     * @param bom
     * @return
     */
    @ApiOperation("保存商品清单")
    @PostMapping("/save")
    public CommResult<Bom> save(@RequestBody Bom bom) {

        Enterprise enterprise = enterpriseService.getCurrent();

        Map<String,Object> params = new HashMap<>();
        params.put("enterpriseId",enterprise.getId());
        params.put("productId",bom.getProductId());
        List<Bom> bomList = bomService.selectList(params);
        if (bomList.size()>0) {
            Bom b = bomList.get(0);
            if (b.getDeleted()==false) {
                return CommResult.error("不能重复添加");
            }
        }
        bom.setEnterpriseId(enterprise.getId());
        bom.setDeleted(false);
        bom.setCreateDate(new Date());
        int affectCount = bomService.save(bom);
        if (affectCount <= 0) {
            return CommResult.error();
        }
        Bom result = bomService.findById(bom.getId());
        return CommResult.success(result);

    }


    /**
     * 批量删除商品清单
     *
     * @param ids
     * @return
     */
    @Log(desc = "批量删除商品清单", type = Log.LOG_TYPE.DEL)
    @ApiOperation("批量删除商品清单,ids用逗号拼接")
    @PostMapping("/del/{ids}")
    public CommResult<Bom> del(@PathVariable String ids) {

        bomService.deleteByIds(ids.split(","));
        return CommResult.success();

    }

    /**
     * 更新商品清单
     *
     * @param bom
     * @return
     */
    @Log(desc = "更新商品清单", type = Log.LOG_TYPE.UPDATE)
    @ApiOperation("更新商品清单")
    @PostMapping("/update")
    public CommResult<Bom> update(@RequestBody Bom bom) {

        Bom b = bomService.selectByPrimaryKey(bom.getId());
        if (!b.getQuantity().equals(bom.getQuantity())) {
            Product product = productService.selectByPrimaryKey(bom.getProductId());
            Goods goods = goodsService.selectByPrimaryKey(product.getGoodsId());
            if (goods.getTotalSale().compareTo(0L)>0) {
               return CommResult.error("不能修改套餐类型");
            }
        }

        int affectCount = bomService.update(bom);
        if (affectCount <= 0){
            return CommResult.error();
        }
        Bom result = bomService.findById(bom.getId());
        return CommResult.success(result);

    }

    /**
     * 添加水票
     *
     * @param productId
     * @return
     */

    @Log(desc = "添加水票", type = Log.LOG_TYPE.UPDATE)
    @ApiOperation("添加水票")
    @PostMapping("/addWater")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "productId", value = "所属商品", dataType = "Long", paramType = "query") ,
            @ApiImplicitParam(name = "productCategoryId", value = "所属分类", dataType = "Long", paramType = "query")
    })
    public CommResult<Bom> addWater(Long productId,Long productCategoryId) {

        Product product = productService.selectByPrimaryKey(productId);
        if (product==null) {
            return CommResult.error("无效商品");
        }

        Enterprise enterprise = enterpriseService.getCurrent();

        Map<String,Object> params = new HashMap<>();
        params.put("enterpriseId",enterprise.getId());
        params.put("type",2);
        params.put("itemProductId",productId);

        List<Bom> bomList = bomService.selectList(params);
        Bom bom = null;

        if (bomList.size()>0) {
            for (Bom b:bomList) {

                if (b.getDeleted()==false) {

                    return CommResult.error("水票已经添加");

                } else {

                    b.setDeleted(false);
                    bomService.updateByPrimaryKeySelective(b);

                    Product prod = productService.selectByPrimaryKey(b.getProductId());
                    prod.setDeleted(false);
                    BeanUtils.copyProperties(product,prod,"goodsId");
                    prod.setName("水票-"+prod.getName());
                    prod.setType(1);
                    prod.setSubType(2);
                    prod.setIsList(true);
                    if (productCategoryId!=null) {
                        prod.setProductCategoryId(productCategoryId);
                    }
                    productService.updateByPrimaryKeySelective(prod);

                    bom = b;

                    break;
                }
            }
        }

        bom = bomService.addWater(product,productCategoryId);
        Bom result = bomService.findById(bom.getId());
        return CommResult.success(result);

    }


}
